import SocketIO from 'socket.io-client'
export default class Socket {
  constructor({ options, store }) {
    this.options = options
    this.sockets = []
    this.vuex = store
  }

  install(Vue) {
    const version = Number(Vue.version.split('.')[0])
    if (version >= 3) {
      Vue.config.globalProperties.$sockets = this.sockets
    } else {
      Vue.prototype.$sockets = this.sockets
    }
  }

  connect(nsp, path, _options = {}) {
    const options = Object.assign(this.options, _options)
    this[nsp] = this.sockets[nsp] = SocketIO(path, options)
    useVuex(this, nsp, this.vuex)
    this[nsp]
      .on('connect', function(event) {
        console.log('连接成功2...')
        _options.onSuccess && _options.onSuccess(event)
      })
      .on('reconnecting', function() {
        console.log('多媒体正在重连...')
      })
      .on('reconnect', function() {
        console.log('多媒体成功重连...')
      })
      .on('reconnect_failed', function(event) {
        console.log('多媒体重连失败...')
        _options.onError && _options.onError(event)
      })
      .on('anything', function(data) {
        console.log('anything', data)
      })
      .on('disconnect', function() {
        console.log('多媒体连接已断开')
      })
      .on('ping', function() {
      })
  }

  removeConnect(key) {}
}

function useVuex(that, nsp, store) {
  const socket = that[nsp]
  if (!isNullObject(store._mutations)) {
    for (let key in store._mutations) {
      let mutationKey = key.split('/').pop()
      let eventName = key.split('_').pop()
      if (mutationKey === `SOCKET_${nsp.toUpperCase()}_${eventName}`) {
        // console.log('========>:socket.on', eventName)
        socket.on(eventName, function(event) {
          store.commit(key, event)
        })
      }
    }
  }
  if (!isNullObject(store._actions)) {
    for (let key in store._actions) {
      let mutationKey = key.split('/').pop()
      let eventName = mutationKey.split('_').pop()
      if (mutationKey === `SOCKET_${nsp.toUpperCase()}_${eventName}`) {
        socket.on(eventName, function(event) {
          store.dispatch(key, event)
        })
      }
    }
  }
}

function isNullObject(obj) {
  return JSON.stringify(obj) === '{}'
}
